<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

const route = useRoute()
const router = useRouter()
const book = ref(null)
const tags = ref([])
const excerpts = ref([])

// 书摘相关
const excerptDialogVisible = ref(false)
const excerptForm = ref({
  excerpt: '',
  thought: ''
})
const isEditingExcerpt = ref(false)
const editingExcerptId = ref(null)

// 获取标签列表
const getTagList = async () => {
  try {
    const response = await request.get('/api/tags')
    if (response.data.code === 200) {
      tags.value = response.data.data.list
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 编辑弹窗相关
const dialogVisible = ref(false)
const editForm = ref({
  title: '',
  author: '',
  cover: '',
  tags: []
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取图书详情
const getBookDetail = async () => {
  try {
    const response = await request.get(`/api/books/${route.params.id}`)
    if (response.data.code === 200) {
      console.log('获取图书详情成功:', response.data)
      book.value = {
        id: response.data.data.book.id,
        title: response.data.data.book.book_name,
        author: response.data.data.book.book_author,
        cover: response.data.data.book.book_img ? response.data.data.book.book_img : '/book-fengmian.png',
        tags: response.data.data.tags || []
      }
    }
  } catch (error) {
    console.error('获取图书详情失败:', error)
  }
}

// 打开编辑弹窗
const openEditDialog = () => {
  editForm.value = {
    title: book.value.title,
    author: book.value.author,
    cover: book.value.cover,
    tags: [...book.value.tags]
  }
  dialogVisible.value = true
}

// 保存编辑
const saveEdit = async () => {
  try {
    const response = await request.put(`/api/books/${book.value.id}`, {
      book_name: editForm.value.title,
      book_author: editForm.value.author,
      book_img: editForm.value.cover,
      tags: editForm.value.tags
    })
    if (response.data.code === 200) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      getBookDetail()
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 获取书摘列表
const getExcerptList = async () => {
  try {
    const response = await request.get(`/api/excerpts/book/${route.params.id}`)
    if (response.data.code === 200) {
      excerpts.value = response.data.data?.list || []
    }
  } catch (error) {
    console.error('获取书摘列表失败:', error)
  }
}

// 打开新增书摘弹窗
const openAddExcerptDialog = () => {
  excerptForm.value = {
    excerpt: '',
    thought: ''
  }
  isEditingExcerpt.value = false
  editingExcerptId.value = null
  excerptDialogVisible.value = true
}

// 打开编辑书摘弹窗
const openEditExcerptDialog = (excerpt) => {
  excerptForm.value = {
    excerpt: excerpt.excerpt,
    thought: excerpt.thought
  }
  isEditingExcerpt.value = true
  editingExcerptId.value = excerpt.id
  excerptDialogVisible.value = true
}

// 保存书摘
const saveExcerpt = async () => {
  try {
    if (isEditingExcerpt.value) {
      // 编辑书摘
      const response = await request.put(`/api/excerpts/${editingExcerptId.value}`, excerptForm.value)
      if (response.data.code === 200) {
        ElMessage.success('编辑成功')
        excerptDialogVisible.value = false
        getExcerptList()
      }
    } else {
      // 新增书摘
      const response = await request.post(`/api/excerpts/book/${book.value.id}`, {
        ...excerptForm.value,
        book_id: book.value.id
      })
      if (response.data.code === 200) {
        ElMessage.success('添加成功')
        excerptDialogVisible.value = false
        getExcerptList()
      }
    }
  } catch (error) {
    console.error('保存书摘失败:', error)
    ElMessage.error('保存失败')
  }
}

onMounted(() => {
  getBookDetail()
  getTagList()
  getExcerptList()
})
</script>

<template>
  <div class="book-detail" v-if="book">
    <div class="back-button" @click="goBack">
      <el-icon><ArrowLeft /></el-icon>
      <span>返回</span>
    </div>
    <div class="book-card">
      <div class="book-cover">
        <img :src="book.cover" :alt="book.title" />
      </div>
      <div class="book-info">
        <h1 class="book-title">《{{ book.title }}》</h1>
        <div class="book-author">作者：{{ book.author }}</div>
        <div class="book-tags" v-if="book && book.tags && book.tags.length > 0">
          <el-tag 
            v-for="tagId in book.tags" 
            :key="tagId"
            class="tag-item"
          >
            {{ tags.find(t => t.id === tagId)?.tag_name || tagId }}
          </el-tag>
        </div>
        <el-button type="primary" class="edit-button" @click="openEditDialog">
          <el-icon><Edit /></el-icon>
          编辑
        </el-button>
      </div>
    </div>

    <!-- 书摘列表 -->
    <div class="book-excerpts">
      <div class="excerpts-header">
        <h2>读书笔记</h2>
        <el-button type="primary" @click="openAddExcerptDialog">
          <el-icon><Plus /></el-icon>
          添加笔记
        </el-button>
      </div>
      <div class="excerpts-list" v-if="excerpts.length > 0">
        <el-card v-for="excerpt in excerpts" :key="excerpt.id" class="excerpt-card">
          <div class="excerpt-content">
            <div class="excerpt-text">{{ excerpt.excerpt }}</div>
            <div class="excerpt-thought" v-if="excerpt.thought">想法：{{ excerpt.thought }}</div>
            <div class="excerpt-footer">
              <span class="excerpt-time">{{ excerpt.created_at }}</span>
              <el-button type="primary" link @click="openEditExcerptDialog(excerpt)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
      <el-empty v-else description="暂无读书笔记" />
    </div>

    <!-- 书摘编辑弹窗 -->
    <el-dialog
      v-model="excerptDialogVisible"
      :title="isEditingExcerpt ? '编辑笔记' : '添加笔记'"
      width="600px"
    >
      <el-form :model="excerptForm" label-width="80px">
        <el-form-item label="摘录">
          <el-input
            v-model="excerptForm.excerpt"
            type="textarea"
            :rows="4"
            placeholder="请输入书摘内容"
          />
        </el-form-item>
        <el-form-item label="想法">
          <el-input
            v-model="excerptForm.thought"
            type="textarea"
            :rows="3"
            placeholder="请输入你的想法（选填）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="excerptDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveExcerpt">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑图书信息"
      width="500px"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="书名">
          <el-input v-model="editForm.title" placeholder="请输入书名" />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="editForm.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="封面图片">
          <el-input v-model="editForm.cover" placeholder="请输入封面图片URL" />
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="editForm.tags"
            multiple
            filterable
            placeholder="请选择标签"
            style="width: 100%"
          >
            <el-option
              v-for="tag in tags"
              :key="tag.id"
              :label="tag.tag_name"
              :value="tag.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.book-detail {
  max-width: 800px;
  margin: 40px auto;
  padding: 20px;
  position: relative;
}

.back-button {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-bottom: 20px;
  width: fit-content;
  color: #409EFF;
  font-size: 14px;
}

.back-button:hover {
  opacity: 0.8;
}

.back-button el-icon {
  margin-right: 5px;
}

.book-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  display: flex;
  overflow: hidden;
}

.book-cover {
  width: 300px;
  height: 400px;
  overflow: hidden;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.book-info {
  flex: 1;
  padding: 30px;
}

.book-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.book-author {
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
}

.book-tags {
  margin-bottom: 10px;
}

.tag-item {
  margin-right: 5px;
}

.edit-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.edit-button .el-icon {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.book-excerpts {
  margin-top: 30px;
}

.excerpts-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.excerpts-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.excerpts-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.excerpt-card {
  border-radius: 8px;
}

.excerpt-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.excerpt-text {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
}

.excerpt-thought {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  white-space: pre-wrap;
}

.excerpt-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  font-size: 14px;
  color: #999;
}
</style>